--[[
-- @Author:      feilong
-- @DateTime:    2020-11-13 23:05:48
-- @Description:
-- @Example:



--]]
local rabbit = require("snex.rabbitmqstomp")

local cjson = require "cjson"
local debug = debug


local M = class("Hander")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function M:ctor()
    local server_config = g.getServerConf()
    local conf = server_config.rabbit
    self.db_info = conf
    self.host = conf[1]
    self.account = conf[2]
    self.exchange = conf[3]

    self.conn = nil
    self:register()
end

--注册本服务里的消息
function M:register()
    g.register("pub", handler(self, self.onPub))
    g.defCallback(self,self.defaultCommand)
end

--从连接池里取一个服务
function M:getConnect()    
    if self.conn then
        return self.conn
    end
    local ok, ret = xpcall(rabbit.connect, debug.traceback, self.host, self.account)
    while not ok do
        g.log:error('failed to connect rabbit',ret, self.host, self.account)
        g.sleep(500)   --one second
        ok,ret = xpcall(rabbit.connect, debug.traceback, self.host, self.account)
    end
    self.conn = ret
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------



function M:onPub(msg, headers, ...)
    local conn = self:getConnect()
    if not conn then
        g.log:debug("getConnect is err")
        return
    end
    if not headers then
        headers = {}
        headers["destination"] = self.exchange.name --交换机名字
        headers["receipt"] = "no_cmd"
        headers["app-id"] = "skynet_rabbitmq"
        headers["persistent"] = "true"
        --headers["content-type"] = "application/json"
        headers["routing-key"] = self.exchange.key --交换机类型要使用headers, 还要绑定队列

        --headers["content-type"] = "text/plain"
        --headers["routing_key"] = "test"
        --headers["routing key"] = "test"
        --headers["routingkey"] = "test"
    end
    --生产
    local res = conn:send(cjson.encode(msg), headers)
    --g.log:debug("published:", res)
    return res

end

function M:defaultCommand(...)
    return self:onPub(...)
end





return M